// 横屏游戏页面
import StockData from '../data/StockData.js';

class GamePage {
  constructor(canvas, ctx, gameManager, api, rootImgUrl) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.gameManager = gameManager;
    this.api = api;
    this.rootImgUrl = rootImgUrl;
    this.stockData = new StockData();
    this.gameScore = 0;
    this.gameTime = 60;
    this.timer = null;
    this.isShowOperation = false;
    this.isGameOver = false;
    this.isEdit = false;
    this.startIcon = wx.createImage();
    this.buyIcon = wx.createImage();
    this.sellIcon = wx.createImage();
    this.changeDiceIcon = wx.createImage();
    this.shareIcon = wx.createImage();
    this.operationBg = wx.createImage();
    this.gameOverBg = wx.createImage();
    this.rightActive = 1
  }

  onEnter() {
    this.loadResources()
    console.log('进入横屏游戏页面');
  }

  onLeave() {
    console.log('离开游戏页面');
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  startGame() {
    this.gameScore = 0;
    this.gameTime = 60;

    this.timer = setInterval(() => {
      this.gameTime--;
      if (this.gameTime <= 0) {
        this.endGame();
      }
    }, 1000);
  }

  update() {
    // 游戏逻辑更新
  }

  loadResources() {
    //买入按钮背景图片
    this.buyIcon.src = this.rootImgUrl + 'buyIcon.png';
    // 卖出按钮背景图片
    this.sellIcon.src = this.rootImgUrl + 'sellIcon.png';
    // 开始按钮背景图
    this.startIcon.src = this.rootImgUrl + 'startIcon.png';
    // 买卖背景图
    this.operationBg.src = this.rootImgUrl + 'gamePop.png';
    // 换股按钮背景图片
    this.changeDiceIcon.src = this.rootImgUrl + 'changeDiceIcon.png';
    // 分享按钮图片
    this.shareIcon.src = this.rootImgUrl + 'share.png';
    // 游戏结束背景图
    this.gameOverBg.src = this.rootImgUrl + 'gameResultPop.png';

    // 资源加载完成后开始渲染
    let loadedCount = 0;
    const totalResources = 7;

    const checkLoaded = () => {
      loadedCount++;
      if (loadedCount === totalResources) {
        this.render();
      }
    };

    this.operationBg.onload = checkLoaded;
    this.gameOverBg.onload = checkLoaded;
    this.buyIcon.onload = checkLoaded;
    this.sellIcon.onload = checkLoaded;
    this.startIcon.onload = checkLoaded;
    this.changeDiceIcon.onload = checkLoaded;
    this.shareIcon.onload = checkLoaded;
  }

  render() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    // 横屏游戏页面背景
    this.ctx.fillStyle = '#2C2D4B';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

    this.drawTopSection();
    // 横屏K线图区域
    this.drawKLineChart();
    this.drawRightSection();
    this.drawBottomSection();
    if (this.isShowOperation) {
      this.popupCenterSection()
    }
    if (this.isGameOver) {
      this.gameOverSection()
    }
  }

  drawTopSection() {
    // 顶部状态栏（深蓝色背景）
    this.ctx.fillStyle = '#2C2D4B';
    this.ctx.fillRect(0, 0, this.canvas.width, 106); // x,y,width,height

    this.ctx.strokeStyle = '#ececec';
    this.ctx.beginPath();
    this.ctx.lineTo(0, 105);
    this.ctx.lineTo(this.canvas.width, 105);
    this.ctx.stroke();

    // 绘制“资产”信息
    this.ctx.fillStyle = '#fff';
    this.ctx.font = '28px Microsoft YaHei-Regular';
    this.ctx.fillText('资产', 136, 20); // x,y
    this.ctx.fillText('100万', 298, 20); // x,y

    // 绘制“资产收益率”信息
    this.ctx.font = '20px Microsoft YaHei-Regular';
    this.ctx.fillText('资产收益率', 136, 65); // x,y
    this.ctx.fillText('6.35%', 300, 65); // x,y

    // 绘制“分享领资金”信息
    this.ctx.fillStyle = '#FCF4C4';
    this.ctx.font = '28px Microsoft YaHei-Regular';
    this.ctx.fillText('分享领资金：5/5', 1040, 40);
    this.ctx.drawImage(this.shareIcon, 1296, 22, 58, 58);// x,y
  }

  drawKLineChart() {
    // K线图区域（黑色背景）
    this.ctx.fillStyle = '#000';
    this.ctx.fillRect(0, 106, this.canvas.width - 170, this.canvas.width - 220); // x,y,width,height

    this.ctx.fillStyle = '#FCF4C4';
    this.ctx.font = '24px Microsoft YaHei-Regular';
    this.ctx.fillText('日线', 56, 128);
    this.ctx.fillStyle = '#5E94E5';
    this.ctx.fillText('MA5', 148, 128);
    this.ctx.fillStyle = '#E55E5E';
    this.ctx.fillText('MA10', 234, 128);
    this.ctx.fillStyle = '#68358B';
    this.ctx.fillText('MA20', 330, 128);
    this.ctx.fillStyle = '#E5C65E';
    this.ctx.fillText('MA30', 428, 128);


    this.ctx.fillStyle = '#FCF4C4';
    this.ctx.textAlign = 'right';
    this.ctx.fillText('涨幅：10.25%  换手：10.25%', this.canvas.width - 200, 128);

    // 示例K线数据
    const klines = [
      { open: 10, close: 12, high: 13, low: 9, color: '#00ff00' }, // 绿色（上涨）
      { open: 12, close: 11, high: 14, low: 10, color: '#ff0000' }, // 红色（下跌）
      // ...更多K线数据
    ];

    // K线间距（示例：n=100，间距15px）
    const klineSpacing = 30;

    klines.forEach((kline, index) => {
      const x = 135 + index * klineSpacing; // K线水平位置（左边界+间距*索引）
      const y = 580 - (kline.close - 9) * 10; // K线垂直位置（底部向上，每1点高度10px）
      const height = (kline.close - kline.open) * 10; // K线高度

      // 绘制开盘-收盘线
      this.ctx.fillStyle = kline.color;
      this.ctx.fillRect(x, y, 10, height); // K线主体

      // 绘制最高-最低线
      this.ctx.fillRect(x + 5, 580 - kline.high * 10, 1, (kline.high - kline.low) * 10); // 最高-最低线
    });

    // 示例均线数据
    const ma5 = [10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10, 11, 12, 13, 14]; // MA5数据
    const ma10 = [9, 10, 11, 12, 13, 9, 10, 11, 12, 13, 9, 10, 11, 12, 13]; // MA10数据
    const ma20 = [8, 9, 10, 11, 12, 8, 9, 10, 11, 12, 8, 9, 10, 11, 12]; // MA20数据
    const ma30 = [7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11]; // MA30数据

    // MA5（黄色）
    this.ctx.strokeStyle = '#ffcc00';
    this.ctx.beginPath();
    ma5.forEach((value, index) => {
      const x = 135 + index * klineSpacing; // 均线水平位置（与K线间距一致）
      const y = 400 - value * 10; // 均线垂直位置（底部向上，每1点高度10px）
      this.ctx.lineTo(x, y);
    });
    this.ctx.stroke();

    // MA10（紫色）
    this.ctx.strokeStyle = '#9933ff';
    this.ctx.beginPath();
    ma10.forEach((value, index) => {
      const x = 135 + index * 20;
      const y = 400 - value * 10;
      this.ctx.lineTo(x, y);
    });
    this.ctx.stroke();

    // MA20（蓝色）
    this.ctx.strokeStyle = '#0099ff';
    this.ctx.beginPath();
    ma20.forEach((value, index) => {
      const x = 135 + index * 20;
      const y = 400 - value * 10;
      this.ctx.lineTo(x, y);
    });
    this.ctx.stroke();

    // MA30（绿色）
    this.ctx.strokeStyle = '#00ff00';
    this.ctx.beginPath();
    ma30.forEach((value, index) => {
      const x = 135 + index * 20;
      const y = 400 - value * 10;
      this.ctx.lineTo(x, y);
    });
    this.ctx.stroke();

    // 示例成交量数据
    const volumes = [100, 150, 200, 250, 260, 100, 150, 200, 250, 220, 100, 150, 200, 250, 260, 100, 150, 200, 250, 260]; // 成交量数据

    volumes.forEach((volume, index) => {
      const x = 135 + index * klineSpacing; // 成交量水平位置（与K线间距一致）
      const y = 636 - volume / 2; // 成交量垂直位置（底部向上，每100对应2px）
      this.ctx.fillStyle = '#00ff00';
      this.ctx.fillRect(x, y, 25, volume * 2); // 成交量柱
    });

    // 绘制买卖信号（S/B）
    this.ctx.fillStyle = '#ff0000';
    this.ctx.font = '32px Microsoft YaHei-Regular';
    this.ctx.fillText('S', 100, 200); // 卖出信号
    this.ctx.fillText('B', 200, 200); // 买入信号
  }

  drawRightSection() {
    // 右侧指标栏背景（深蓝色）
    this.ctx.fillStyle = '#2C2D4B';
    this.ctx.fillRect(this.canvas.width - 185, 106, 184, 536); // x,y,width,height

    this.ctx.strokeStyle = '#ececec';
    this.ctx.beginPath();
    this.ctx.lineTo(this.canvas.width - 185, 106);
    this.ctx.lineTo(this.canvas.width - 185, 636);
    this.ctx.stroke();

    const fontColor = '#fff'
    const activeFontColor = '#FFE861'

    // 绘制“成交量”指标
    this.ctx.fillStyle = this.rightActive == 1 ? activeFontColor : fontColor;
    this.ctx.textAlign = 'left';
    this.ctx.font = '32px Microsoft YaHei-Regular';
    this.ctx.fillText('成交量', this.canvas.width - 140, 188); // x,y（右侧指标栏内偏移）

    // 绘制“MACD”指标
    this.ctx.fillStyle = this.rightActive == 2 ? activeFontColor : fontColor;
    this.ctx.fillText('MACD', this.canvas.width - 140, 292); // x,y

    // 绘制“KDJ”指标
    this.ctx.fillStyle = this.rightActive == 3 ? activeFontColor : fontColor;
    this.ctx.fillText('KDJ', this.canvas.width - 140, 396); // x,y

    // 绘制“BOLL”指标
    this.ctx.fillStyle = this.rightActive == 4 ? activeFontColor : fontColor;
    this.ctx.fillText('BOLL', this.canvas.width - 140, 500); // x,y
  }

  drawBottomSection() {
    // 底部操作栏（深蓝色背景）
    this.ctx.font = '32px Microsoft YaHei-Regular';
    this.ctx.fillStyle = '#2C2D4B';
    this.ctx.fillRect(0, 636, this.canvas.width, 114); // x,y,width,height

    this.ctx.strokeStyle = '#ececec';
    this.ctx.beginPath();
    this.ctx.lineTo(0, 636);
    this.ctx.lineTo(this.canvas.width, 636);
    this.ctx.stroke();

    // “买”按钮（红色）
    this.ctx.fillStyle = '#fff';
    this.ctx.drawImage(this.buyIcon, 64, 650, 239, 88);
    this.ctx.fillText('买', 160, 672); // x,y

    // “卖”按钮（绿色）
    this.ctx.drawImage(this.sellIcon, 298, 650, 239, 88);
    this.ctx.fillText('卖', 394, 672); // x,y

    // “换股”按钮（紫色）
    this.ctx.drawImage(this.changeDiceIcon, 1116, 658, 171, 72);
    this.ctx.fillText('换股', 1172, 672); // x,y

    // “开始”按钮（蓝色）
    this.ctx.drawImage(this.startIcon, 1322, 650, 239, 88);
    this.ctx.fillStyle = '#fff';
    this.ctx.fillText('开始', 1400, 672); // x,y
  }

  popupCenterSection() {
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'; // 半透明黑色
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.drawImage(this.operationBg, this.canvas.width / 2 - this.operationBg.width / 2, this.canvas.height / 2 - this.operationBg.height / 2, 1002, 560);
  }

  gameOverSection() {
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'; // 半透明黑色
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.drawImage(this.gameOverBg, this.canvas.width / 2 - this.gameOverBg.width / 2, this.canvas.height / 2 - this.gameOverBg.height / 2, 1222, 567);

    // 游戏结束确定按钮
    this.ctx.fillStyle = '#fff';
    this.ctx.drawImage(this.buyIcon, 700, 546, 239, 88);
    this.ctx.fillText('确定', 778, 560); // x,y
  }

  handleTouch(x, y) {
    // 检查是否点击了返回按钮
    if (x >= 17 && x <= 37 && y >= 17 && y <= 37) {
      this.gameManager.switchPage('main');
    }

    if (x >= 623 && x <= 645 && y >= 55 && y <= 75) {
      if (this.isShowOperation) {
        this.isShowOperation = false
      }
    }

    if (x >= 350 && x <= 462 && y >= 273 && y <= 310) {
      this.isGameOver = false
    }

    if (this.isShowOperation || this.isGameOver) {
      return; // 如果弹窗开了，什么也不做
    }

    if (x >= 744 && x <= 800 && y >= 94 && y <= 114) {
      this.rightActive = 1
    }

    if (x >= 744 && x <= 800 && y >= 146 && y <= 166) {
      this.rightActive = 2
    }

    if (x >= 744 && x <= 800 && y >= 198 && y <= 218) {
      this.rightActive = 3
    }

    if (x >= 744 && x <= 800 && y >= 250 && y <= 270) {
      this.rightActive = 4
    }

    // 检查看涨按钮
    if (x >= 32 && x <= 152 && y >= 329 && y <= 373) {
      console.log('点击了买')
      this.isShowOperation = true
      //this.makePrediction('up');
    }

    // 检查看跌按钮
    if (x >= 149 && x <= 269 && y >= 329 && y <= 373) {
      console.log('点击了卖')
      this.isGameOver = true
      //this.makePrediction('down');
    }
  }

  handleKeyDown(e) {
    switch (e.keyCode) {
      case 37: // 左箭头
        this.makePrediction('up');
        break;
      case 39: // 右箭头
        this.makePrediction('down');
        break;
    }
  }

  handleTouchEnd(e) {

  }

  handleTouchMove(x, y) { }

  makePrediction(direction) {
    const nextData = this.stockData.getNextData();
    const actualDirection = nextData.close >= nextData.open ? 'up' : 'down';

    if (direction === actualDirection) {
      this.gameScore += 10;
      console.log('预测正确！+10分');
    } else {
      this.gameScore = Math.max(0, this.gameScore - 5);
      console.log('预测错误！-5分');
    }

    this.stockData.moveToNext();
  }

  endGame() {
    clearInterval(this.timer);

    // 更新用户数据
    const userData = this.gameManager.getUserData();
    userData.totalGames = (userData.totalGames || 0) + 1;
    userData.coins += Math.floor(this.gameScore / 10);

    if (this.gameScore > userData.bestScore) {
      userData.bestScore = this.gameScore;
    }

    this.gameManager.updateUserData(userData);
    this.gameManager.switchPage('gameOver');
  }
}

export default GamePage;